package com.avic.rong.activity.mine;

import android.Manifest;
import android.app.Activity;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.Build;
import android.os.Environment;
import android.provider.MediaStore;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.content.FileProvider;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.avic.rong.BaseActivity;
import com.avic.rong.BuildConfig;
import com.avic.rong.MainActivity;
import com.avic.rong.R;
import com.avic.rong.api.UploadPhotoApi;
import com.avic.rong.api.mine.GetDetailInfoApi;
import com.avic.rong.api.mine.MinePageApi;
import com.avic.rong.api.mine.OwnMessageApi;
import com.avic.rong.api.mine.UpdatePictureApi;
import com.avic.rong.auditcertification.activity.EnterpriseSuccessActivity;
import com.avic.rong.auditcertification.activity.MyCertificationActivity;
import com.avic.rong.auditcertification.activity.PersonAuthenticationHomeActivity;
import com.avic.rong.bean.mine.Bean;
import com.avic.rong.bean.mine.DetailInfoBean;
import com.avic.rong.bean.mine.MinePageBean;
import com.avic.rong.bean.mine.OwnMessageBean;
import com.avic.rong.course.showapi.publishDelApi;
import com.avic.rong.utils.DialogCustom;
import com.avic.rong.utils.SDCardUtils;
import com.avic.rong.utils.SharedPreferencesUtil;
import com.avic.rong.utils.ConstantsUtils;
import com.avic.rong.utils.RoundImageDrawable;
import com.avic.rong.utils.ToastTools;
import com.avic.rong.wedgit.StringUtil;
import com.avic.rong.wedgit.customWedgit.SheetDialog;
import com.avic.rong.wedgit.permissionschecker.PermissionChecker;
import com.bumptech.glide.Glide;
import com.bumptech.glide.load.DataSource;
import com.bumptech.glide.load.engine.GlideException;
import com.bumptech.glide.request.RequestListener;
import com.bumptech.glide.request.RequestOptions;
import com.bumptech.glide.request.target.SimpleTarget;
import com.bumptech.glide.request.target.Target;
import com.bumptech.glide.request.transition.Transition;
import com.example.minato.minastore.BaseResultEntity;
import com.example.minato.minastore.http.HttpManager;
import com.example.minato.minastore.listener.HttpOnNextListener;
import com.example.minato.minastore.utils.AppUtils;
import com.example.minato.minastore.utils.CircleProgressDialog;
import com.google.gson.Gson;
import com.luck.picture.lib.PictureSelector;
import com.luck.picture.lib.config.PictureConfig;
import com.luck.picture.lib.config.PictureMimeType;
import com.luck.picture.lib.entity.LocalMedia;
import com.orhanobut.logger.Logger;
import com.trello.rxlifecycle2.components.support.RxAppCompatActivity;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;
import io.reactivex.Observable;
import io.reactivex.ObservableEmitter;
import io.reactivex.ObservableOnSubscribe;
import io.reactivex.functions.Consumer;
import io.reactivex.schedulers.Schedulers;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

import static com.avic.rong.activity.product.OnlineCServiceActivity.recycleBitmap;
import static com.avic.rong.utils.Utils.getContext;

//账号设置-个人信息
public class OwnMessageActivity extends BaseActivity {


    private String[] PERMISSIONS = new String[]{
            Manifest.permission.CAMERA,
            Manifest.permission.WRITE_EXTERNAL_STORAGE
    };
    @BindView(R.id.rl_header)
    RelativeLayout rl_header;
    @BindView(R.id.rl_username)
    RelativeLayout rl_username;
    @BindView(R.id.right_nc)
    ImageView right_nc;
    @BindView(R.id.rl_nickname)
    RelativeLayout rl_nickname;
    @BindView(R.id.right_email)
    ImageView right_email;
    @BindView(R.id.rl_email)
    RelativeLayout rl_email;
    @BindView(R.id.right_info)
    ImageView right_info;
    @BindView(R.id.rl_introduce)
    LinearLayout rl_introduce;
    @BindView(R.id.rl_detail_news)
    RelativeLayout rl_detail_news;
    @BindView(R.id.rl_company_name)
    LinearLayout rl_company_name;
    @BindView(R.id.rl_company_address)
    LinearLayout rl_company_address;
    /* @BindView(R.id.btn_commit)
     Button btn_commit;*/
    @BindView(R.id.iv_header)
    ImageView iv_header;
    @BindView(R.id.tv_username)
    TextView tv_username;
    @BindView(R.id.tv_nickname)
    TextView tv_nickname;
    @BindView(R.id.tv_email)
    TextView tv_email;
    @BindView(R.id.tv_introduce)
    TextView tv_introduce;
    @BindView(R.id.tv_companyname)
    TextView tv_companyname;
    @BindView(R.id.tv_companyaddress)
    TextView tv_companyaddress;
    private String email;
    private String nickname;
    private String username;
    private String introduce;
    private OwnMessageBean data;

    private String imgUrl;
    private String login_token;
    private SharedPreferencesUtil sharedPreferencesUtil;
    private SheetDialog sheetDialog;
    private PermissionChecker permissionChecker;
    private int TAKE_CAMERA_PHOTO = 200;
    private String cameraPath;
    private DetailInfoBean detailInfoBean;
    private CircleProgressDialog circleProgressDialog;

    @Override
    protected int getContentViewId() {
        return R.layout.activity_own_message;
    }

    @Override
    protected void initView() {
        tvTitle.setText("个人信息");
        ivRight.setBackgroundResource(R.mipmap.slh);

        sharedPreferencesUtil = SharedPreferencesUtil.getInstance();
        permissionChecker = new PermissionChecker(this);

        circleProgressDialog = new CircleProgressDialog(context);
        if (!EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().register(this);
        }

        email = tv_email.getText().toString().trim();
        nickname = tv_nickname.getText().toString().trim();
        username = tv_username.getText().toString().trim();
        introduce = tv_introduce.getText().toString().trim();


        if (SharedPreferencesUtil.isLogin()) {
            login_token = SharedPreferencesUtil.getLoginToken();
        }

        OwnMessageApi ownMessageApi = new OwnMessageApi(this, ownMessageListener);
        ownMessageApi.setArgument(login_token);
        ownMessageApi.setCancel(false);
        ownMessageApi.setShowProgress(true);
        HttpManager.getInstance().doHttpDeal(ownMessageApi);

        GetDetailInfoApi getDetailInfoApi = new GetDetailInfoApi(this, getDetailInfoListener);
        getDetailInfoApi.setToken(login_token);
        HttpManager.getInstance().doHttpDeal(getDetailInfoApi);

        Log.e("tag", "onCreate: " + OwnMessageActivity.this.getPackageName());
    }

    //详细地址
    HttpOnNextListener<BaseResultEntity> getDetailInfoListener = new HttpOnNextListener<BaseResultEntity>() {

        @Override
        public void onNext(BaseResultEntity baseResultEntity) {
            if (baseResultEntity.getCode().equals(ConstantsUtils.STATUS_SUCCESS_0000)) {
                detailInfoBean = (DetailInfoBean) baseResultEntity.getData();
                if (detailInfoBean != null) {
                    String oldaddress = detailInfoBean.getAddress();//详细地址
                    String oldcompanyName = detailInfoBean.getCompanyName();
                    String oldcompanyAddress = detailInfoBean.getCompanyAddress();
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            if (!StringUtil.isEmpty(oldcompanyName)) {
                                tv_companyname.setText(oldcompanyName);//公司名称
                            }
                            if (!StringUtil.isEmpty(oldaddress) && !StringUtil.isEmpty(oldcompanyAddress)) {
                                tv_companyaddress.setText(oldcompanyAddress + oldaddress);//所在地区
                            }
                        }
                    });
                }
            }
        }
    };


    @Override
    protected void addListener() {
        ivBack.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String nickName = tv_nickname.getText().toString().trim();
                Intent intent = getIntent();
                intent.putExtra("logo", imgUrl);
                intent.putExtra("name", nickName);
                setResult(100, intent);
                finish();
            }
        });
    }

    @Override
    public void onBackPressed() {
        if (mSwipeBackHelper.isSliding()) {
            return;
        }
        String nickName = tv_nickname.getText().toString().trim();
        Intent intent = getIntent();
        intent.putExtra("logo", imgUrl);
        intent.putExtra("name", nickName);
        setResult(100, intent);
        finish();
        mSwipeBackHelper.backward();
        overridePendingTransition(R.anim.keep, R.anim.out_from_right);
    }

    HttpOnNextListener<BaseResultEntity> ownMessageListener = new HttpOnNextListener<BaseResultEntity>() {
        @Override
        public void onNext(BaseResultEntity baseResultEntity) {
            if (baseResultEntity.getCode().equals(ConstantsUtils.STATUS_SUCCESS_0000)) {
                data = (OwnMessageBean) baseResultEntity.getData();

                if (data.getEmail() != null) {
                    tv_email.setText(data.getEmail());
                }

                if (data.getIntroduction() != null) {
                    tv_introduce.setText(data.getIntroduction());
                }
                tv_nickname.setText(data.getNickName());
                tv_username.setText(data.getUserName());
                String logo = data.getLogo();
                if (logo == null) {
                    String userPhoto = SharedPreferencesUtil.getInstance(OwnMessageActivity.this).getUserPhoto();
                    logo = userPhoto;
                }
                Glide.with(OwnMessageActivity.this).applyDefaultRequestOptions(RequestOptions.circleCropTransform().error(R.mipmap.deafult_image_header))
                        .load(logo).into(iv_header);

            } else {
                Toast toast = Toast.makeText(OwnMessageActivity.this, baseResultEntity.getMsg(), Toast.LENGTH_SHORT);
                toast.setGravity(Gravity.CENTER, 0, 0);
                toast.show();
            }
        }
    };

    public static Intent queryIntent(Context context) {
        Intent intent = new Intent(context, OwnMessageActivity.class);
        return intent;
    }

    /*
     * 接受地址信息
     * */
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void getAddress(Bean bean) {
        tv_companyname.setText(bean.getCompanyName());
        tv_companyaddress.setText(bean.getAddress() + bean.getXxMsg());
    }


    @OnClick({R.id.right, R.id.rl_header, R.id.rl_username, R.id.right_nc, R.id.rl_nickname, R.id.right_email, R.id.rl_email, R.id.right_info, R.id.rl_introduce, R.id.right_xxmsg, R.id.rl_detail_news, R.id.rl_company_name, R.id.rl_company_address/*R.id.btn_commit*/})
    public void onClick(View v) {
        switch (v.getId()) {
            default:
                break;
            case R.id.rl_username://修改用户名
                setDialog();
                break;
            case R.id.rl_header://修改头像
                showFileChooser();
                break;
            case R.id.rl_nickname://修改昵称
                String nickname = tv_nickname.getText().toString().trim();
                Intent intent = UpNameActivity.queryIntent(this);
                intent.putExtra("nickName", nickname);
                startActivityIfNeeded(intent, 4);
                break;
            case R.id.rl_email://修改邮箱
                String email = tv_email.getText().toString().trim();
                Intent intent1 = UpEmailActivity.queryIntent(this);
                intent1.putExtra("email", email);
                startActivityIfNeeded(intent1, 4);
                break;
            case R.id.rl_introduce://修改简介
                String introduce = tv_introduce.getText().toString().trim();
                Intent intent2 = UpInfoActivity.queryIntent(this);
                intent2.putExtra("info", introduce);
                startActivityIfNeeded(intent2, 4);
                break;
            case R.id.rl_detail_news://修改详细信息
                startActivity(DetailInfoActivity.queryIntent(OwnMessageActivity.this));
                break;
            /*case R.id.btn_commit://保存个人信息
                commit();
                break;*/
        }
    }

    private void setDialog() {
        DialogCustom.showDoubleDialog(context, "", "请在融融号认证页面编辑您的融融号名称", "取消", "确定", new DialogCustom.CustomDialogDouble() {
            @Override
            public void rightButtonClicked() {

                MinePageApi minePageApi = new MinePageApi(OwnMessageActivity.this, minePageListener);
                minePageApi.setArgument(SharedPreferencesUtil.getLoginToken(), SharedPreferencesUtil.getInstance(getContext()).getIMEID());
                minePageApi.setShowProgress(true);
                minePageApi.setCancel(!true);
                HttpManager.getInstance().doHttpDeal(minePageApi);
            }

            @Override
            public void leftButtonClicked() {

            }
        });
    }

    HttpOnNextListener<BaseResultEntity> minePageListener = new HttpOnNextListener<BaseResultEntity>() {

        @Override
        public void onNext(BaseResultEntity baseResultEntity) {
            if (baseResultEntity.getCode().equals(ConstantsUtils.STATUS_SUCCESS_0000)) {
                MinePageBean data = (MinePageBean) baseResultEntity.getData();

                if (0 == data.getRongRongStatus()) {
                    startActivity(MyCertificationActivity.queryIntent(getContext()));  //认证列表
                } else {
                    if (0 == data.getType() || 1 == data.getType()) {
                        startActivity(EnterpriseSuccessActivity.queryIntent(getContext()));// 企业认证
                    } else {
                        startActivity(PersonAuthenticationHomeActivity.queryIntent(getContext()));  //个人认证
                    }
                }

            }
        }

        @Override
        public void onError(Throwable e) {
//            String networkState = NetWorkUtils.getNetworkState(getContext());
//            Toast toast = Toast.makeText(getContext(), e.getMessage(), Toast.LENGTH_SHORT);
//            toast.setGravity(Gravity.CENTER, 0, 0);
//            toast.show();
        }
    };


 /*   //保存到sp中
    private void commit() {

        SharedPreferencesUtil sharedPreferencesUtil = SharedPreferencesUtil.getInstance(this);
        if (imgUrl == null){
            imgUrl = SharedPreferencesUtil.getInstance(OwnMessageActivity.this).getUserPhoto();
        }
        data.setLogo(imgUrl);
        sharedPreferencesUtil.setUserInfo(data);
        Toast.makeText(this, "保存成功", Toast.LENGTH_SHORT).show();
        EventBus.getDefault().post(data);
        finish();
    }*/


    private void showFileChooser() {
        sheetDialog = new SheetDialog.Builder(this).setTitle(ConstantsUtils.EMPTY_STR)
                .addMenu("拍照", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();
                        if (sheetDialog != null && sheetDialog.isShowing()) {
                            sheetDialog.dismiss();
                        }
                        if (permissionChecker.isLackPermissions(PERMISSIONS)) {
                            permissionChecker.requestPermissions();
                        } else {
                            cameraPath = SDCardUtils.getSDCardPath() + "/temp.png";
                            File file = new File(cameraPath);
                            Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
                            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
                                intent.putExtra(MediaStore.EXTRA_OUTPUT, FileProvider.getUriForFile(getContext(), BuildConfig.APPLICATION_ID + ".provider", file));
                            } else {
                                intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(file));
                            }

                            intent.putExtra("return-data", false);
                            intent.putExtra("outputFormat", Bitmap.CompressFormat.PNG.toString());
                            intent.putExtra("noFaceDetection", true);
                            startActivityForResult(intent, TAKE_CAMERA_PHOTO);
                        }
                    }
                })
                .addMenu("从相册中选择", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();
                        if (sheetDialog != null && sheetDialog.isShowing()) {
                            sheetDialog.dismiss();
                        }
                        if (permissionChecker.isLackPermissions(PERMISSIONS)) {
                            permissionChecker.requestPermissions();
                        } else {
                            startPickPhoto();
                        }
                    }
                }).setCancelListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        sheetDialog.dismiss();
                    }
                }).create();
        sheetDialog.setOnDismissListener(new DialogInterface.OnDismissListener() {
            @Override
            public void onDismiss(DialogInterface dialog) {
            }
        });
        sheetDialog.show();


    }

    //压缩并上传图片
    private Bitmap bitmap;
    private File uploadFile;

    private void compressPictureUpload(String imagePath) {
        circleProgressDialog.show();
        BitmapFactory.Options options = new BitmapFactory.Options();
        options.inSampleSize = 2;
        options.inPreferredConfig = Bitmap.Config.RGB_565;
        options.inPurgeable = true;
        options.inInputShareable = true;
        bitmap = BitmapFactory.decodeFile(imagePath, options);

        Observable.create(new ObservableOnSubscribe<String>() {
            @Override
            public void subscribe(ObservableEmitter<String> emitter) throws Exception {
                uploadFile = compressImage(bitmap);
                emitter.onNext(uploadFile.getAbsolutePath());
            }
        }).subscribeOn(Schedulers.computation()).observeOn(Schedulers.newThread()).subscribe(new Consumer<String>() {
            @Override
            public void accept(String temp) throws Exception {
                upLoad(temp);
                recycleBitmap(bitmap);
            }
        });
    }

    /**
     * 压缩图片（质量压缩）
     *
     * @param bitmap
     */
    public static File compressImage(Bitmap bitmap) {
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        bitmap.compress(Bitmap.CompressFormat.PNG, 100, baos);//质量压缩方法，这里100表示不压缩，把压缩后的数据存放到baos中
        int options = 100;
        while (baos.toByteArray().length / 1024 > 5 * 1024 && options > 10) {  //循环判断如果压缩后图片是否大于500kb,大于继续压缩
            baos.reset();//重置baos即清空baos
            options -= 10;//每次都减少10
            Logger.i("-----------------------------option:" + options);
            if (options > 0) {//options 的范围为0--100
                bitmap.compress(Bitmap.CompressFormat.PNG, options, baos);//这里压缩options%，把压缩后的数据存放到baos中
            }
            long length = baos.toByteArray().length;
        }
        SimpleDateFormat format = new SimpleDateFormat("yyyyMMddHHmmss");
        Date date = new Date(System.currentTimeMillis());
        String filename = format.format(date);
        File file = new File(Environment.getExternalStorageDirectory(), filename + ".png");
        try {
            FileOutputStream fos = new FileOutputStream(file);
            try {
                fos.write(baos.toByteArray());
                fos.flush();
                fos.close();
            } catch (IOException e) {
                Logger.e(e.getMessage());
                e.printStackTrace();
            }
        } catch (FileNotFoundException e) {
            Logger.e(e.getMessage());
            e.printStackTrace();
        }
        recycleBitmap(bitmap);
        return file;
    }


    //选择照片
    private void startPickPhoto() {

        PictureSelector.create(this)
                .openGallery(PictureMimeType.ofImage())// 全部.PictureMimeType.ofAll()、图片.ofImage()、视频.ofVideo()、音频.ofAudio()
                .theme(R.style.picture_default_style)// 主题样式设置 具体参考 values/styles   用法：R.style.picture.white.style
//                    .maxSelectNum(3)
                .maxSelectNum(1)
                .minSelectNum(1)// 最小选择数量
                .imageSpanCount(3)// 每行显示个数
                .selectionMode(PictureConfig.SINGLE)// 多选 or 单选
                .previewImage(true)// 是否可预览图片
                .isCamera(false)// 是否显示拍照按钮
                .isZoomAnim(false)// 图片列表点击 缩放效果 默认true
                .enableCrop(true)// 是否裁剪
                .compress(true)// 是否压缩
                .circleDimmedLayer(true)
                .glideOverride(260, 260)// glide 加载宽高，越小图片列表越流畅，但会影响列表图片浏览的清晰度
                .hideBottomControls(true)// 是否显示uCrop工具栏，默认不显示
                .freeStyleCropEnabled(true)// 裁剪框是否可拖拽
                .showCropFrame(false)// 是否显示裁剪矩形边框 圆形裁剪时建议设为false
                .showCropGrid(false)// 是否显示裁剪矩形网格 圆形裁剪时建议设为false
                .minimumCompressSize(100)// 小于100kb的图片不压缩
                .forResult(PictureConfig.CHOOSE_REQUEST);//结果回调onActivityResult code
    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (resultCode == Activity.RESULT_OK) {
            if (requestCode == TAKE_CAMERA_PHOTO) {//拍照
//                ToastTools.showToast(OnlineCServiceActivity.this,"asdfasdf" + cameraPath);
                compressPictureUpload(cameraPath);
            } else if (requestCode == PictureConfig.CHOOSE_REQUEST) {//选择照片

                // 图片选择结果回调
                // 例如 LocalMedia 里面返回三种path
                // 1.media.getPath(); 为原图path
                // 2.media.getCutPath();为裁剪后path，需判断media.isCut();是否为true
                // 3.media.getCompressPath();为压缩后path，需判断media.isCompressed();是否为true
                // 如果裁剪并压缩了，已取压缩路径为准，因为是先裁剪后压缩的
                List<LocalMedia> tempList = PictureSelector.obtainMultipleResult(data);
                for (LocalMedia media : tempList) {
                    if (media.isCompressed() && media.isCut()) {
                        Logger.i("图片-----》", media.getCompressPath());
                        circleProgressDialog.show();
                        upLoad(media.getCompressPath());
                    }
                }
//                ToastTools.showToast(OnlineCServiceActivity.this,"asddddddddddd");
            }
            sheetDialog.cancel();
        } else if (requestCode == 4) {
            if (resultCode == 100) {
                String name = data.getStringExtra("nickName_new");
                tv_nickname.setText(name);
            } else if (resultCode == 200) {
                String email_new = data.getStringExtra("email_new");
                tv_email.setText(email_new);
            } else if (resultCode == 300) {
                String info_new = data.getStringExtra("info_new");
                tv_introduce.setText(info_new);
            }
        }
    }

    /*
     * 上传头像
     * */
    public void upLoad(String photoPath) {
        UploadPhotoApi uploadPhotoApi = new UploadPhotoApi(this, httpOnNextListener);
        File file = new File(photoPath);
        RequestBody requestBody = RequestBody.create(MediaType.parse("image/*"), file);
        MultipartBody.Part part = MultipartBody.Part.createFormData("file", file.getName(), requestBody);
        uploadPhotoApi.setPart(part);
        HttpManager.getInstance().doHttpDeal(uploadPhotoApi);
    }

    HttpOnNextListener<BaseResultEntity> httpOnNextListener = new HttpOnNextListener<BaseResultEntity>() {
        @Override
        public void onNext(BaseResultEntity baseResultEntity) {
            if (baseResultEntity.getCode().equals(ConstantsUtils.STATUS_SUCCESS_0000)) {
                imgUrl = (String) baseResultEntity.getData();
                RequestOptions apply = new RequestOptions().
                        error(R.mipmap.icon_message_photo).
                        apply(RequestOptions.circleCropTransform()).
                        placeholder(R.mipmap.ic_launcher)
                        .skipMemoryCache(true);
                Glide.with(OwnMessageActivity.this).applyDefaultRequestOptions(apply)
                        .load(imgUrl)
                        .listener(new RequestListener<Drawable>() {
                            @Override
                            public boolean onLoadFailed(@Nullable GlideException e, Object model, Target<Drawable> target, boolean isFirstResource) {
                                return false;
                            }

                            @Override
                            public boolean onResourceReady(Drawable resource, Object model, Target<Drawable> target, DataSource dataSource, boolean isFirstResource) {
                                iv_header.setImageDrawable(resource);
                                ToastTools.showPublicToast("上传成功了");
                                upDateLogo(imgUrl);
                                return false;
                            }
                        }).into(iv_header);
            } else {
                Toast.makeText(OwnMessageActivity.this, baseResultEntity.getMsg() + "    " + baseResultEntity.getCode(), Toast.LENGTH_SHORT).show();
            }
        }
    };

    public void upDateLogo(String imgUrl) {
        UpdatePictureApi updatePicture = new UpdatePictureApi(this, new MyUpdatePhotoListener(imgUrl));
        updatePicture.setArgument(login_token, imgUrl);
        HttpManager.getInstance().doHttpDeal(updatePicture);
    }


    public class MyUpdatePhotoListener extends HttpOnNextListener<BaseResultEntity> {
        String imgPath;

        public MyUpdatePhotoListener(String imgPath) {
            this.imgPath = imgPath;
        }

        @Override
        public void onNext(BaseResultEntity baseResultEntity) {
            if (!baseResultEntity.getCode().equals(ConstantsUtils.STATUS_SUCCESS_0000)) {
                ToastTools.showPublicToast(baseResultEntity.getMsg());
            }
            circleProgressDialog.dismiss();
            Log.e("wcx", "imgPath: " + imgPath);
        }
    }

    ;


    @Override
    protected void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }
}
